import axios from 'axios'
import { normalize } from 'normalizr'
import { feedsArraySchema } from './schema'

axios.defaults.baseURL = 'http://localhost:3000/api'
axios.defaults.withCredentials = true

// 拦截
axios.interceptors.response.use((response) => {
  if (typeof response.data === 'string') {
    return response.data
  }
  if (response.data.ok) {
    return response.data.data
  } else {
    throw new Error(response.data.error)
  }
})
axios.interceptors.request.use(async (config) => {
  await delay(Math.random() * 1000 + 500)
  return config
})

function delay(ms) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, ms);
  })
}

export function fetchFeedsPage(page=1) {
  return axios.get('/feeds?page=' + page).then(data => {
    data.feeds = normalize(data.feeds, feedsArraySchema)
    return data
  })
}

const fetchTop10 = (type) => () => axios.get('/top10/'+type)
export const fetchH24Top10 = fetchTop10('h24')
export const fetchH72Top10 = fetchTop10('h72')
export const fetchH168Top10 = fetchTop10('h168')

export const getCaptcha = () => axios.get('/captcha')
